package org.example.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.example.controller.common.permission.PermissionObject;
import org.example.controller.common.permission.PermissionUtils;
import org.example.mapper.RoleInfoMapper;
import org.example.model.common.AppHttpCodeEnum;
import org.example.model.common.PageResponseDto;
import org.example.model.common.ResponseResult;
import org.example.model.user.dtos.PermissionDto;
import org.example.model.user.dtos.RoleInfoDto;
import org.example.model.user.dtos.UserIdentityDto;
import org.example.model.user.entities.RoleInfo;
import org.example.model.user.vos.AddRoleInfoVo;
import org.example.model.user.vos.SearchRoleInfoVo;
import org.example.service.user.RoleInfoService;
import org.example.utils.UserIdThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色信息服务层实现
 */
@Service
@Transactional
@Slf4j
public class RoleInfoServiceImpl extends ServiceImpl<RoleInfoMapper, RoleInfo> implements RoleInfoService {

    @Autowired
    private RoleInfoMapper roleInfoMapper;

    /**
     * 添加一条角色信息
     */
    @Override
    public ResponseResult<Boolean> InsertRoleInfo(AddRoleInfoVo addRoleInfoVo) throws ClassNotFoundException, IllegalAccessException {
        ResponseResult<Boolean> result = new ResponseResult<>();
        // 参数审查
        if (addRoleInfoVo == null) {
            // 缺少参数
            result.error(AppHttpCodeEnum.PARAM_REQUIRE.getCode(), AppHttpCodeEnum.PARAM_REQUIRE.getErrorMessage());
            return result;
        }
        RoleInfo roleInfo = new RoleInfo();
        // 设置默认权限
        List<PermissionObject> permissionDtoList = PermissionUtils.GetAllPermissions();
        roleInfo.setPermissionList(JSON.toJSONString(permissionDtoList));
        BeanUtils.copyProperties(addRoleInfoVo, roleInfo);
        this.HandleRoleInfoBasic(roleInfo);
        Boolean flag = roleInfoMapper.insert(roleInfo) > 0;
        result.ok(AppHttpCodeEnum.SUCCESS.getCode(), flag, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        return result;
    }

    //处理添加角色信息时共有信息的处理
    private void HandleRoleInfoBasic (RoleInfo roleInfo) {
        // 获取进程中的用户数据
        UserIdentityDto userIdentityDto = UserIdThreadLocalUtils.getUser();
        if (roleInfo.getId() == 0) {
            roleInfo.setCreateUserId(userIdentityDto.getId());
            roleInfo.setCreateTime(LocalDateTime.now());
            roleInfo.setIsDeleted(false);
        }
        roleInfo.setUpdateUserId(userIdentityDto.getId());
        roleInfo.setUpdateTime(LocalDateTime.now());
    }

    /**
     * 根据id修改一条角色信息
     */
    @Override
    public ResponseResult<Boolean> UpdateRoleInfoById(AddRoleInfoVo addRoleInfoVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        // 参数审查
        if (addRoleInfoVo == null || addRoleInfoVo.getId() <= 0) {
            // 缺少参数
            result.error(AppHttpCodeEnum.PARAM_REQUIRE.getCode(), AppHttpCodeEnum.PARAM_REQUIRE.getErrorMessage());
            return result;
        }
        RoleInfo roleInfo = roleInfoMapper.selectById(addRoleInfoVo.getId());
        BeanUtils.copyProperties(addRoleInfoVo, roleInfo);
        this.HandleRoleInfoBasic(roleInfo);
        Boolean flag = roleInfoMapper.updateById(roleInfo) > 0;
        result.ok(AppHttpCodeEnum.SUCCESS.getCode(), flag, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        return result;
    }

    /**
     * 分页根据条件（角色名，角色状态）获取角色信息列表
     */
    @Override
    public ResponseResult<PageResponseDto<List<RoleInfoDto>>> SelectRoleInfoByConditions(SearchRoleInfoVo searchRoleInfoVo) {
        ResponseResult<PageResponseDto<List<RoleInfoDto>>> result = new ResponseResult<>();
        // 参数审查
        if (searchRoleInfoVo == null) {
            // 缺少参数 查询条件
            result.error(AppHttpCodeEnum.PARAM_REQUIRE.getCode(), AppHttpCodeEnum.PARAM_REQUIRE.getErrorMessage());
            return result;
        }
        // 查询条件
        LambdaQueryWrapper<RoleInfo> roleQuery = new LambdaQueryWrapper<>();
        roleQuery.eq(RoleInfo::getIsDeleted, false);
        // 创建时间倒排
        roleQuery.orderByDesc(RoleInfo::getCreateTime);
        // 角色名模糊查询，角色状态精确查询
        roleQuery.like(StringUtils.isNotBlank(searchRoleInfoVo.getName()), RoleInfo::getName, searchRoleInfoVo.getName())
                .eq(searchRoleInfoVo.getStatus() != null, RoleInfo::getStatus, searchRoleInfoVo.getStatus());
        // 分页处理数据
        IPage<RoleInfo> page = new Page<>(searchRoleInfoVo.getPageIndex(), searchRoleInfoVo.getPageSize());
        IPage<RoleInfo> roleListByPage = roleInfoMapper.selectPage(page, roleQuery);
        // 应返回数据
        PageResponseDto<List<RoleInfoDto>> pageResponseDto = new PageResponseDto<>();
        pageResponseDto.setSize(roleInfoMapper.selectCount(roleQuery).intValue());
        List<RoleInfo> roleInfoRecords = roleListByPage.getRecords();
        List<RoleInfoDto> roleInfoDtos = new ArrayList<>();
        RoleInfoDto roleInfoDto = null;
        for (RoleInfo roleInfo : roleInfoRecords) {
            roleInfoDto = new RoleInfoDto();
            BeanUtils.copyProperties(roleInfo, roleInfoDto);
            roleInfoDtos.add(roleInfoDto);
        }
        pageResponseDto.setData(roleInfoDtos);
        result.ok(AppHttpCodeEnum.SUCCESS.getCode(), pageResponseDto, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        return result;
    }

    /**
     * 根据id删除一条角色信息
     */
    @Override
    public ResponseResult<Boolean> DeleteRoleInfoById(int id) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        // 参数审查
        if (id <= 0) {
            // 缺少参数
            result.error(AppHttpCodeEnum.PARAM_REQUIRE.getCode(), AppHttpCodeEnum.PARAM_REQUIRE.getErrorMessage());
            return result;
        }
        RoleInfo roleInfo = roleInfoMapper.selectById(id);
        roleInfo.setIsDeleted(true);
        this.HandleRoleInfoBasic(roleInfo);
        Boolean flag = roleInfoMapper.updateById(roleInfo) > 0;
        result.ok(AppHttpCodeEnum.SUCCESS.getCode(), flag, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        return result;
    }

    /**
     * 根据id获取当前角色的权限列表
     */
    @Override
    public ResponseResult<PermissionDto> GetPermissionListById(int id) throws JsonProcessingException, ClassNotFoundException, IllegalAccessException {
        ResponseResult<PermissionDto> result = new ResponseResult<>();
        // 参数审查
        if (id <= 0) {
            // 缺少参数
            result.error(AppHttpCodeEnum.PARAM_REQUIRE.getCode(), AppHttpCodeEnum.PARAM_REQUIRE.getErrorMessage());
            return result;
        }
        RoleInfo roleInfo = roleInfoMapper.selectById(id);
        PermissionDto permissionDto = new PermissionDto();
        BeanUtils.copyProperties(roleInfo, permissionDto);
        ObjectMapper objectMapper = new ObjectMapper();
        List<PermissionObject> permissionObjects = objectMapper.readValue(roleInfo.getPermissionList(), objectMapper.getTypeFactory().constructCollectionType(List.class, PermissionObject.class));
//        permissionDto.setPermissionDtoList(this.handleNewPermissionList(permissionObjects));
        permissionDto.setPermissionDtoList(permissionObjects);
        result.ok(AppHttpCodeEnum.SUCCESS.getCode(), permissionDto, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        return result;
    }

    // 获取最新权限列表，将当前角色权限更新到最新的权限列表
    private List<PermissionObject> handleNewPermissionList (List<PermissionObject> databasePermissionList) throws ClassNotFoundException, IllegalAccessException {
        List<PermissionObject> permissionDtoList = PermissionUtils.GetAllPermissions();
        // todo 对比两个权限列表，更新权限列表
        return databasePermissionList;
    }

    /**
     * 根据id修改当前角色的权限列表
     */
    @Override
    public ResponseResult<Boolean> UpdatePermissionListById(PermissionDto permissionDto) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        // 参数审查
        if (permissionDto == null || permissionDto.getId() <= 0) {
            // 缺少参数
            result.error(AppHttpCodeEnum.PARAM_REQUIRE.getCode(), AppHttpCodeEnum.PARAM_REQUIRE.getErrorMessage());
            return result;
        }
        RoleInfo roleInfo = roleInfoMapper.selectById(permissionDto.getId());
        BeanUtils.copyProperties(permissionDto, roleInfo);
        roleInfo.setPermissionList(JSON.toJSONString(permissionDto.getPermissionDtoList()));
        this.HandleRoleInfoBasic(roleInfo);
        Boolean flag = roleInfoMapper.updateById(roleInfo) > 0;
        result.ok(AppHttpCodeEnum.SUCCESS.getCode(), flag, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        return result;
    }
}
